var app = getApp(); //获取app.js
const api = require('../../config/config.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    url: app.globalData.url,
    index:0,
    navHeight: app.globalData.navHeight, //按照每个页面加,默认不加
    //点击修改不喜欢/喜欢
    teamer: [
    {teamerId: 1, name: "JFramev", icon: "/images/team/JFrame.png", position: "网管", likesNum: 1, isLike:1},
    {teamerId: 2, name: "JFramev", icon: "/images/team/JFrame.png", position: "网管", likesNum: 1,isLike:0},
    {teamerId: 3, name: "JFramev", icon: "/images/team/JFrame.png", position: "网管", likesNum: 0,isLike:0},
    {teamerId: 4, name: "JFramev", icon: "/images/team/JFrame.png", position: "网管", likesNum: 0,isLike:0},
    {teamerId: 5, name: "JFramev", icon: "/images/team/JFrame.png", position: "网管", likesNum: 1,isLike:0},
    {teamerId: 6, name: "JFramev", icon: "/images/team/JFrame.png", position: "网管", likesNum: 0,isLike:0}
    ],
    likeIdList: []
  },
  doLike(e) {
    let that = this;
    let loginFlag = wx.getStorageSync('loginFlag');
    //用户登录
    if (loginFlag) {
      wx.checkSession({
        // session_key 有效(为过期)
        success: function () {
          // 直接从Storage中获取用户信息
          let userStorageInfo = wx.getStorageSync('userInfo');
          if (userStorageInfo) {
            app.userInfo = userStorageInfo;
            //和userStorgeInfo没什么区别，待会查一下这个Json.parse()有什么用
          } else {
            that.showInfo('缓存信息缺失');
            console.error('登录成功后将用户信息存在Storage的userStorageInfo字段中，该字段丢失');
          }

        },
        // session_key 过期
        fail: function () {
          // session_key过期
          that.doLogin();
        }
      });
    } else {
      // 无登录态
      that.doLogin();
    }
    if (loginFlag) {
      let teamer = that.data.teamer;
      if (teamer[e.currentTarget.dataset.index].isLike == 0) {
        wx.request({
          url: api.doTeamLikeUrl,
          method: 'POST',
          data: {
            loginFlag: loginFlag,
            teamerId: teamer[e.currentTarget.dataset.index].teamerId,
            status: 1 //1点赞
          },
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          success: function (res) {
            if (res.data.status = 200) {
              teamer[e.currentTarget.dataset.index].isLike = 1;
              teamer[e.currentTarget.dataset.index].likesNum++;
              that.setData({
                teamer
              })
              wx.showToast({
                title: "点赞成功!",
                icon: 'none'
              })
            }
          },
          fail: function (error) {
            that.showInfo('请求失败');
          }
        });
      } else {
        wx.showModal({
          title: '提示',
          content: '是否取消喜爱',
          success(res) {
            if (res.confirm) {
              wx.request({
                url: api.doTeamLikeUrl,
                method: 'POST',
                data: {
                  loginFlag: loginFlag,
                  teamerId: teamer[e.currentTarget.dataset.index].teamerId,
                  status:0 //1点赞
                },
                header: {
                  'content-type': 'application/x-www-form-urlencoded'
                },
                success: function (res) {
                  if (res.data.status = 200) {
                    teamer[e.currentTarget.dataset.index].isLike = 0
                    teamer[e.currentTarget.dataset.index].likesNum--;
                    that.setData({
                      teamer
                    })
                  }
                },
                fail: function (error) {
                  that.showInfo('请求失败');
                }
              });

            } else if (res.cancel) {}
          }
        })
      }
    }


  },
  // 登录动作
  doLogin: function (callback = () => {}) {
    wx.showLoading({
      title: '登录中...',
      mask: true
    });
    let that = this;
    wx.login({
      success: function (loginRes) {
        if (loginRes.code) {
          /* 
           * @desc: 获取用户信息 期望数据如下 
           *
           * @param: userInfo       [Object]
           * @param: rawData        [String]
           * @param: signature      [String]
           * @param: encryptedData  [String]
           * @param: iv             [String]
           **/
          wx.getUserInfo({
            withCredentials: true, // 非必填, 默认为true
            success: function (infoRes) {
              console.log(infoRes, '>>>')
              // 请求服务端的登录接口
              wx.request({
                url: api.loginUrl,
                data: {
                  code: loginRes.code, // 临时登录凭证
                  rawData: infoRes.rawData, // 用户非敏感信息
                  signature: infoRes.signature, // 签名
                  encryptedData: infoRes.encryptedData, // 用户敏感信息
                  iv: infoRes.iv // 解密算法的向量
                },
                success: function (res) {
                  that.showInfo('login success', 'success')
                  res = res.data
                   console.log(res);
                  if (res.result == 0) {
                    let res1 = res.data;
                    app.userInfo = res1.userInfo;
                    // console.log(res1)
                    // console.log(res1.sKey);
                    // console.log(res1.userInfo);
                    // console.log(JSON.stringify(res1.userInfo));
                    // console.log(JSON.parse(res1.userInfo));
                    wx.setStorageSync('userInfo', res1.userInfo);
                    wx.setStorageSync('loginFlag', res1.loginFlag);
                    that.refreshTeamer();
                    //console.log("a1");
                    callback();
                    wx.hideLoading();
                  } else {
                    that.showInfo(res.errmsg);
                  }
                },
                fail: function (error) {
                  that.showInfo('登录失败，无法点赞');
                  console.log(error);
                }
              });
            },

            fail: function (error) {
              // 获取 userInfo 失败，去检查是否未开启权限
              wx.hideLoading();
              that.checkUserInfoPermission();
            }
          });

        } else {
          // 获取 code 失败
          that.showInfo('登录失败');
          console.log('调用wx.login获取code失败');
        }
      },

      fail: function (error) {
        // 调用 wx.login 接口失败
        that.showInfo('接口调用失败');
        console.log(error);
      }
    });
  },
  // 检查用户信息授权设置
  checkUserInfoPermission: function (callback = () => {}) {
    wx.getSetting({
      success: function (res) {
        if (!res.authSetting['scope.userInfo']) {
          wx.openSetting({
            success: function (authSetting) {
              console.log(authSetting)
            }
          });
        }
      },
      fail: function (error) {
        console.log(error);
      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.refreshTeamer();
  },
  // 封装 wx.showToast 方法
  showInfo: function (info = 'error', icon = 'none') {
    wx.showToast({
      title: info,
      icon: icon,
      duration: 1500,
      mask: true
    });
  },
  refreshTeamer:function(){
    let that=this;
    //加载时获取teamerList likeIdList(仅当用户登入时获取)
    wx.request({
      url: api.getTeamPageUrl,
      method: 'POST',
      data: {
        loginFlag: wx.getStorageSync('loginFlag'),
        index:that.data.index
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        console.log(res.data.data);
        var likeIdList = res.data.data.likeIdList;
        var teamer = res.data.data.teamer;
         //this.setData.
    for (let i = 0; i < likeIdList.length; i++) {
      for (let j = 0; j < teamer.length; j++) {
        if (likeIdList[i] == teamer[j].teamerId) {
          teamer[j].isLike = 1;
        }
      }
    }
    that.setData({
      teamer
    })
      },
      fail: function (error) {
        that.showInfo('请求失败');
      }
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})